/**
 * Copyright (C) 2022 - 长期
 * All rights reserved.
 * <p>
 * 版权所有 (C) 中国烟草总公司
 */
package com.itzhoun.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author zhounan
 * @date 2024/01/22 15:43
 * @Description
 */
public class JWTUtil {

    private static final Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    //过期时间5分钟
    private static final long EXPIRE_TIME = 5 * 60 * 1000;


    /**
     *
     * @author zhounan
     * @Create 2024/1/22 15:46
     * @Description 获取用户名 无需secret也能获取
     * @param token
     * @return java.lang.String
     */
    public static String getUserName(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("username").asString();
    }

    /**
     *
     * @author zhounan
     * @Create 2024/1/22 15:53
     * @Description 生成签名 5分钟过期
    * @param username 用户名
    * @param secret 用户的密码
    * @return java.lang.String
     */
    public static String sign(String username, String secret){
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        //将用户信息附带上
        return JWT.create()
                .withClaim("username", username)
                .withExpiresAt(date).sign(algorithm);
    }

    /**
     *
     * @author zhounan
     * @Create 2024/1/22 15:58
     * @Description 验证token是否有效
     * @param token token
     * @param username 用户名
     * @param secret 密钥
     * @return boolean
     */
    public static boolean verify(String token, String username, String secret){
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
        DecodedJWT verify = verifier.verify(token);
        return true;
    }
}
